﻿/***************************************************************************
	Copyright (C) 2010 RapidWebDev Organization (Author: Eunge, Legal Name: Jian Liu, Email: eunge.liu@gmail.com)

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ***************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Threading;
using BaoJianSoft.Common;
using BaoJianSoft.Web.Extensions.Controls;
using BaoJianSoft.Web.Extensions.Properties;

namespace BaoJianSoft.Web.Extensions.DynamicPages
{
    /// <summary>
    /// Aspx base page for workshop.
    /// </summary>
    public abstract class WorkshopAspxPageBase : ContentPage
    {
        private static Type EditingModesType = typeof(EditingModes);

        private delegate void BuildModuleEventHandler();
        private Dictionary<ModuleTypes, BuildModuleEventHandler> buildModuleEventHandlers;

        private Control @moduleQuery;
        private Control @moduleGridView;
        private Control @moduleDetailPanel;
        private Control @moduleSummaryPanel;

        /// <summary>
        /// Gets create button instance.
        /// </summary>
        public LinkButton @CreateButton { get; private set; }

        /// <summary>
        /// Gets dynamic generated query panel control.
        /// </summary>
        public QueryPanel @QueryPanel { get; private set; }

        /// <summary>
        /// Gets dynamic generated gridview panel control.
        /// </summary>
        public GridViewPanel @GridViewPanel { get; private set; }

        /// <summary>
        /// Gets dynamic generated detail panel control.
        /// </summary>
        public TemplatePanel @DetailPanel { get; private set; }

        /// <summary>
        /// Gets dynamic generated summary panel control.
        /// </summary>
        public TemplatePanel @SummaryPanel { get; private set; }

        /// <summary>
        /// Page header text of content page.
        /// </summary>
        public override string HeaderText { get { return this.WorkshopObject.Configuration.Title; } }

        /// <summary>
        /// Page access permission key.
        /// </summary>
        public override string PermissionValue { get { return this.WorkshopObject.Configuration.PermissionValue; } }

        /// <summary>
        /// Get ContentAdvisor instance from content advisor container by query string.
        /// </summary>
        public IPageWorkshop WorkshopObject
        {
            get
            {
                try
                {
                    return ConfigurationObjects.GetWorkshop(SessionManager.ObjectId);
                }
                catch (Exception exp)
                {
                    Logger.Instance(this).Error(exp);
                    Response.Redirect(WebUtility.PageNotFoundUrl);
                    return null;
                }
            }
        }

        /// <summary>
        /// Constructor with binding module building methods to module types in order.
        /// </summary>
        public WorkshopAspxPageBase()
        {
            this.buildModuleEventHandlers = new Dictionary<ModuleTypes, BuildModuleEventHandler>();
            this.buildModuleEventHandlers.Add(ModuleTypes.Query, new BuildModuleEventHandler(this.BuildQueryPanel));
            this.buildModuleEventHandlers.Add(ModuleTypes.GridView, new BuildModuleEventHandler(this.BuildGridViewPanel));
            this.buildModuleEventHandlers.Add(ModuleTypes.DetailPanel, new BuildModuleEventHandler(this.BuildDetailPanel));
            this.buildModuleEventHandlers.Add(ModuleTypes.SummaryPanel, new BuildModuleEventHandler(this.BuildSummaryPanel));
        }

        /// <summary>
        /// Add controls into main section panel.
        /// </summary>
        /// <param name="control"></param>
        protected abstract void AddControls(Control control);

        /// <summary>
        /// Get message panel control to display user faced message.
        /// </summary>
        protected abstract MessagePanel @MessagePanel { get; }

        /// <summary>
        /// Raises the System.Web.UI.Control.Init event to initialize the page.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            this.WorkshopObject.BeforeInit(this);

            base.OnInit(e);

            this.Title = this.HeaderText;
            this.BuildWorkshop();
            this.WorkshopObject.Messaging += (sender, args) =>
                {
                    switch (args.MessageType)
                    {
                        case MessageTypes.Confirm:
                            this.MessagePanel.ShowConfirm(args.MessageBody);
                            break;
                        case MessageTypes.Error:
                            this.MessagePanel.ShowError(args.MessageBody);
                            break;
                        case MessageTypes.Warning:
                            this.MessagePanel.ShowWarning(args.MessageBody);
                            break;
                    }
                };

            this.EnsureChildControls();
        }

        /// <summary>
        /// Raises the System.Web.UI.Control.Load event.
        /// </summary>
        /// <param name="e">event handler</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.WorkshopObject.OnLoaded(this);
        }

        /// <summary>
        /// Raises the System.Web.UI.Page.LoadComplete event at the end of the page load stage.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // try to get current entity id.
                string currentEntityId = Request[PageWorkshop.CURRENT_ENTITY_ID];
                if (Kit.IsEmpty(currentEntityId))
                {
                    object currentEntityIdValue = SessionManager.Current.GetSession(PageWorkshop.CURRENT_ENTITY_ID);
                    if (currentEntityIdValue != null)
                    {
                        currentEntityId = currentEntityIdValue.ToString();
                    }
                }

                // if current entity id is specified by query string or session value
                if (!Kit.IsEmpty(currentEntityId))
                {
                    GridViewPrimaryKeyFieldEventArgs arg = new GridViewPrimaryKeyFieldEventArgs(currentEntityId);
                    EditingModes editingMode = EditingModes.None;

                    // try to get editing mode from query string
                    string editingModeValue = Request[PageWorkshop.EDITING_MODE];
                    if (!Kit.IsEmpty(editingModeValue) && Enum.IsDefined(EditingModesType, editingModeValue))
                    {
                        editingMode = (EditingModes)Enum.Parse(EditingModesType, editingModeValue);
                    }

                    // if editing mode is not gotten from query string, now trying to get from session
                    if (editingMode == EditingModes.None)
                    {
                        editingMode = SessionManager.Current.GetSession<EditingModes>(PageWorkshop.EDITING_MODE);
                    }

                    // Fires GridViewEditing events only if the editing mode is "Edit" explicitly.
                    // The default action of editing is view.
                    object sender = this.@GridViewPanel == null ? (object)this : (object)this.@GridViewPanel.GridView;
                    if (editingMode == EditingModes.Edit)
                    {
                        this.OnGridViewEditing(sender, arg);
                    }
                    else
                    {
                        this.OnGridViewViewing(sender, arg);
                    }
                }
                else
                {
                    int pageIndex = SessionManager.Current.GetSession<int>(@GridViewPanel.CURRENT_PAGE_INDEX);

                    string predicate = null;
                    object[] predicateParameters = null;
                    if (this.@QueryPanel != null)
                    {
                        predicate = this.@QueryPanel.CurrentQueryEventArgs.Predicate;
                        predicateParameters = this.@QueryPanel.CurrentQueryEventArgs.PredicateParameters;
                    }

                    this.@GridViewPanel.DataBind(predicate, pageIndex, predicateParameters);
                }
            }
        }

        /// <summary>
        /// Raises the System.Web.UI.Control.PreRender event.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            this.WorkshopObject.OnPreRende(this);
            base.OnPreRender(e);
        }

        private void BuildWorkshop()
        {
            if (this.WorkshopObject.Configuration.Modules != null)
            {
                foreach (ModuleTypes moduleType in this.WorkshopObject.Configuration.Modules)
                    this.buildModuleEventHandlers[moduleType]();
            }

            this.SetButtonsVisibility();
        }

        private void BuildQueryPanel()
        {
            if (this.WorkshopObject.Configuration.Query == null)
            {
                return;
            }

            this.@moduleQuery = new Panel() { ID = "PanelQuery" };
            this.AddControls(this.@moduleQuery);

            this.@QueryPanel = new QueryPanel() { Configuration = this.WorkshopObject.Configuration.Query };
            this.@QueryPanel.Querying += new EventHandler<QueryEventArgs>(this.OnQuerying);
            ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(this.@QueryPanel);

            this.@moduleQuery.Controls.Add(this.@QueryPanel);
        }

        private void BuildGridViewPanel()
        {
            if (this.WorkshopObject.Configuration.GridView == null)
            {
                return;
            }

            this.@moduleGridView = new Container() { ID = "ContainerGridView" };
            this.AddControls(this.@moduleGridView);

            HtmlGenericControl h4Header = new HtmlGenericControl("h4") { ID = "H4GridView", InnerText = string.Format(Resources.QueryResultLabel, this.WorkshopObject.Configuration.GridView.EntityName) };
            this.@moduleGridView.Controls.Add(h4Header);

            HtmlGenericControl divGridViewButtons = new HtmlGenericControl("div");
            divGridViewButtons.Style["text-align"] = "right";
            divGridViewButtons.Style["padding-right"] = "4px";
            divGridViewButtons.Style["padding-bottom"] = "4px";
            this.@moduleGridView.Controls.Add(divGridViewButtons);

            // Decide whether to create "CREATE" button
            if (this.WorkshopObject.Configuration.CreateButton != null)
            {
                this.@CreateButton = new NewIconButton()
                {
                    ID = "NewIconButtonAddObjects",
                    Configuration = this.WorkshopObject.Configuration.CreateButton,
					ToolTip = string.Format(Resources.NewButtonToolTip, this.WorkshopObject.Configuration.GridView.EntityName),
                    Text = string.Format(Resources.NewButtonText, this.WorkshopObject.Configuration.GridView.EntityName)
                };

                this.@CreateButton.Click += new EventHandler(this.OnCreating);
                divGridViewButtons.Controls.Add(this.@CreateButton);
                divGridViewButtons.Controls.Add(new HtmlGenericControl("span") { InnerText = " " });
                ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(this.@CreateButton);
            }

            this.BuildGenericButtons(divGridViewButtons);

            this.@GridViewPanel = new GridViewPanel() { Configuration = this.WorkshopObject.Configuration.GridView };
            this.@GridViewPanel.Viewing += new EventHandler<GridViewPrimaryKeyFieldEventArgs>(this.OnGridViewViewing);
            this.@GridViewPanel.Editing += new EventHandler<GridViewPrimaryKeyFieldEventArgs>(this.OnGridViewEditing);
            this.@GridViewPanel.Deleting += new EventHandler<GridViewPrimaryKeyFieldEventArgs>(this.OnGridViewDeleting);
            this.@GridViewPanel.ButtonsBinding += new EventHandler<GridViewButtonBindingEventArgs>(this.OnGridViewButtonsBinding);
            this.@GridViewPanel.CheckBoxBinding += new EventHandler<GridViewCheckBoxBindingEventArgs>(this.OnGridViewPanelCheckBoxBinding);
            this.@GridViewPanel.DataSourceLoading += new EventHandler<DataSourceLoadEventArgs>(this.OnGridViewDataSourceLoading);
            this.@moduleGridView.Controls.Add(this.@GridViewPanel);
        }

        private void BuildDetailPanel()
        {
            if (this.WorkshopObject.Configuration.DetailPanel == null)
            {
                return;
            }

            this.@moduleDetailPanel = new Panel() { ID = "PanelDetailPanel" };
            this.AddControls(this.@moduleDetailPanel);

            bool isTransparentDetailPanel = false;
            bool.TryParse(Request[PageWorkshop.TRANSPARENT_DETAIL_PANEL], out isTransparentDetailPanel);
            this.@DetailPanel = new TemplatePanel(new AttachChildControlsEventHandler(this.WorkshopObject.OnAttachDetailPanelControls))
            {
                HeaderText = this.WorkshopObject.Configuration.DetailPanel.HeaderText,
                SkinPath = this.WorkshopObject.Configuration.DetailPanel.SkinPath,
                Transparent = isTransparentDetailPanel
            };

            this.@DetailPanel.Saving += new EventHandler(this.OnSaving);
            this.@DetailPanel.Cancelling += new EventHandler(this.OnCancelling);
            ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(this.@DetailPanel);

            this.@moduleDetailPanel.Controls.Add(this.@DetailPanel);
        }

        private void BuildSummaryPanel()
        {
            if (this.WorkshopObject.Configuration.SummaryPanel == null)
            {
                return;
            }

            this.@moduleSummaryPanel = new Panel() { ID = "PanelSummaryPanel" };
            this.AddControls(this.@moduleSummaryPanel);

            bool isTransparentSummaryPanel = false;
            bool.TryParse(Request[PageWorkshop.TRANSPARENT_SUMMARY_PANEL], out isTransparentSummaryPanel);

            this.@SummaryPanel = new TemplatePanel(new AttachChildControlsEventHandler(this.WorkshopObject.OnAttachDetailPanelControls))
            {
                HeaderText = this.WorkshopObject.Configuration.SummaryPanel.HeaderText,
                SkinPath = this.WorkshopObject.Configuration.SummaryPanel.SkinPath,
                Transparent = isTransparentSummaryPanel
            };

            this.@SummaryPanel.Saving += new EventHandler(this.OnSubmitSummaryPanel);
            ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(this.@SummaryPanel);

            this.@moduleSummaryPanel.Controls.Add(this.@SummaryPanel);
        }

        /// <summary>
        /// 在GridView section中创建用户自定义按钮，本方法依赖于BuildGridViewPanel
        /// </summary>
        /// <param name="container"></param>
        private void BuildGenericButtons(Control container)
        {
			if (this.WorkshopObject.Configuration.CustomButtons == null || this.WorkshopObject.Configuration.CustomButtons.Count == 0)
            {
                return;
            }

            Repeater repeaterCustomButtons = new Repeater() { ID = "RepeaterCustomButtons" };
            int customButtonIndex = 0;
            repeaterCustomButtons.ItemDataBound += (sender, e) =>
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    if (customButtonIndex++ > 0)
                        e.Item.Controls.Add(new HtmlGenericControl("span") { InnerHtml = " " });

					ButtonConfiguration customButtonConfiguration = e.Item.DataItem as ButtonConfiguration;
					ConfigurableLinkButton configurableLinkButton = new ConfigurableLinkButton { ID = "CustomButton_" + customButtonConfiguration.CommandArgument, Configuration = customButtonConfiguration };
                    ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(configurableLinkButton);
                    e.Item.Controls.Add(configurableLinkButton);
                }
            };

            repeaterCustomButtons.ItemCommand += new RepeaterCommandEventHandler(OnGenericButtonsCommand);
            repeaterCustomButtons.DataSource = this.WorkshopObject.Configuration.CustomButtons;
            repeaterCustomButtons.DataBind();

            ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(repeaterCustomButtons);
            container.Controls.Add(repeaterCustomButtons);
        }

        private void SetButtonsVisibility()
        {
            this.SetQueryPanelVisibility(true);
            this.SetSummaryPanelVisibility(true);
            this.SetGridViewVisibility(true);
            this.SetDetailPanelVisibility(false);

            if (this.@DetailPanel != null)
            {
                this.@DetailPanel.ButtonSave.Visible = this.WorkshopObject.Configuration.DetailPanel.SaveButton != null;
                if (this.WorkshopObject.Configuration.DetailPanel.SaveButton != null)
                    this.@DetailPanel.ButtonSave.Text = this.WorkshopObject.Configuration.DetailPanel.SaveButton.Text ?? Resources.SaveButtonText;

                this.@DetailPanel.ButtonCancel.Visible = this.WorkshopObject.Configuration.DetailPanel.CancelButton != null;
                if (this.WorkshopObject.Configuration.DetailPanel.CancelButton != null)
                    this.@DetailPanel.ButtonCancel.Text = this.WorkshopObject.Configuration.DetailPanel.CancelButton.Text ?? Resources.CancelButtonText;
            }

            if (this.@SummaryPanel != null)
            {
                this.@SummaryPanel.ButtonSave.Visible = this.WorkshopObject.Configuration.SummaryPanel.SaveButton != null;
                if (this.WorkshopObject.Configuration.SummaryPanel.SaveButton != null)
                    this.@SummaryPanel.ButtonSave.Text = this.WorkshopObject.Configuration.DetailPanel.SaveButton.Text ?? Resources.SaveButtonText;

                this.@SummaryPanel.ButtonCancel.Visible = false;
            }
        }

        void OnQuerying(object sender, QueryEventArgs e)
        {
            try
            {
                this.@GridViewPanel.DataBind(e.Predicate, 0, e.PredicateParameters);

                this.SetSummaryPanelVisibility(true);
                this.SetGridViewVisibility(true);
                this.SetDetailPanelVisibility(false);
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnCreating(object sender, EventArgs e)
        {
            try
            {
                this.SetSummaryPanelVisibility(false);
                this.SetGridViewVisibility(false);
                this.SetDetailPanelVisibility(true);

                SessionManager.Current.SetSession(PageWorkshop.CURRENT_ENTITY_ID, null);
                this.WorkshopObject.OnCreateBlankDetailPanel();
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnGenericButtonsCommand(object source, RepeaterCommandEventArgs e)
        {
            string buttonId = e.CommandArgument.ToString();
            IEnumerable<string> checkedEntityIdCollection = null;

            try
            {
                if (this.WorkshopObject.Configuration.GridView.EnabledCheckBoxField)
                {
                    checkedEntityIdCollection = this.@GridViewPanel.CheckedEntityIds;
                }

                this.WorkshopObject.OnGenericButtonClicked(buttonId, checkedEntityIdCollection);
                this.@GridViewPanel.DataBind(0);
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnGridViewDataSourceLoading(object sender, DataSourceLoadEventArgs e)
        {
            try
            {
				this.WorkshopObject.OnQuerying(e);
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnGridViewButtonsBinding(object sender, GridViewButtonBindingEventArgs e)
        {
            try
            {
                this.WorkshopObject.OnBindingGridViewButtons(e);
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnGridViewPanelCheckBoxBinding(object sender, GridViewCheckBoxBindingEventArgs e)
        {
            try
            {
                this.WorkshopObject.OnBindingGridViewCheckBox(e);
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnGridViewDeleting(object sender, GridViewPrimaryKeyFieldEventArgs e)
        {
            try
            {
                this.WorkshopObject.OnDeleting(e.PrimaryKey);
                this.@GridViewPanel.DataBind();
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnGridViewEditing(object sender, GridViewPrimaryKeyFieldEventArgs e)
        {
            try
            {
                this.SetSummaryPanelVisibility(false);
                this.SetGridViewVisibility(false);
                this.SetDetailPanelVisibility(true);

                SessionManager.Current.SetSession(PageWorkshop.CURRENT_ENTITY_ID, e.PrimaryKey);
                SessionManager.Current.SetSession(PageWorkshop.EDITING_MODE, EditingModes.Edit);

                if (this.@DetailPanel != null)
                {
                    this.@DetailPanel.ButtonSave.Visible = this.WorkshopObject.Configuration.DetailPanel.SaveButton != null;
                    this.@DetailPanel.ButtonCancel.Visible = this.WorkshopObject.Configuration.DetailPanel.CancelButton != null;
                }

                this.WorkshopObject.OnShowEditableDetailPanel(e.PrimaryKey);
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnGridViewViewing(object sender, GridViewPrimaryKeyFieldEventArgs e)
        {
            try
            {
                this.SetSummaryPanelVisibility(false);
                this.SetGridViewVisibility(false);
                this.SetDetailPanelVisibility(true);

                SessionManager.Current.SetSession(PageWorkshop.CURRENT_ENTITY_ID, e.PrimaryKey);
                SessionManager.Current.SetSession(PageWorkshop.EDITING_MODE, EditingModes.View);

                // 在view状态下始终不显示[保存]按钮
                if (this.@DetailPanel != null)
                {
                    this.@DetailPanel.ButtonSave.Visible = false;
                    this.@DetailPanel.ButtonCancel.Visible = this.WorkshopObject.Configuration.DetailPanel.CancelButton != null;
                }

                this.WorkshopObject.OnShowViewableDetailPanel(e.PrimaryKey);
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnSaving(object sender, EventArgs e)
        {
            try
            {
                string message = null;
                SavingTypes savingType = this.GetSavingType();
                switch (savingType)
                {
                    case SavingTypes.Add:
                        message = this.WorkshopObject.OnValidating();
                        if (!string.IsNullOrEmpty(message)) throw new InvalidOperationException(message);
                        this.WorkshopObject.OnSaving();
                        break;
                    case SavingTypes.Update:
                        string selectedEntityId = SessionManager.Current.GetSession(PageWorkshop.CURRENT_ENTITY_ID) as string;
                        message = this.WorkshopObject.OnValidating(selectedEntityId);
                        if (!string.IsNullOrEmpty(message)) throw new InvalidOperationException(message);
                        this.WorkshopObject.OnSaving(selectedEntityId);
                        break;
                }

                this.SetSummaryPanelVisibility(true);
                this.SetGridViewVisibility(true);
                this.SetDetailPanelVisibility(false);

                SessionManager.Current.SetSession(PageWorkshop.CURRENT_ENTITY_ID, null);
                this.@GridViewPanel.DataBind(0);
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnCancelling(object sender, EventArgs e)
        {
            try
            {
                this.SetSummaryPanelVisibility(true);
                this.SetGridViewVisibility(true);
                this.SetDetailPanelVisibility(false);

                this.WorkshopObject.OnCancelling();
                SessionManager.Current.SetSession(PageWorkshop.CURRENT_ENTITY_ID, null);

                if (this.@GridViewPanel != null)
                    this.@GridViewPanel.DataBind();
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        void OnSubmitSummaryPanel(object sender, EventArgs e)
        {
            try
            {
                IEnumerable<string> checkedEntityIdCollection = this.@GridViewPanel.CheckedEntityIds;
                this.WorkshopObject.OnSubmitSummaryPanel(checkedEntityIdCollection);

                this.SetSummaryPanelVisibility(true);
                this.SetGridViewVisibility(true);
                this.SetDetailPanelVisibility(false);

                SessionManager.Current.SetSession(PageWorkshop.CURRENT_ENTITY_ID, null);
                this.@GridViewPanel.DataBind(0);
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException exp)
            {
                this.MessagePanel.ShowWarning(exp.Message);
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                this.MessagePanel.ShowError(exp);
            }
        }

        private void SetGridViewVisibility(bool visible)
        {
            if (this.@moduleGridView == null) return;
			this.@moduleGridView.Visible = visible;
        }

        private void SetDetailPanelVisibility(bool visible)
        {
            if (this.@moduleDetailPanel == null) return;
			this.@moduleDetailPanel.Visible = visible;
        }

        private void SetSummaryPanelVisibility(bool visible)
        {
            if (this.@moduleSummaryPanel == null) return;
			this.@moduleSummaryPanel.Visible = visible;
        }

        private void SetQueryPanelVisibility(bool visible)
        {
            if (this.@moduleQuery == null) return;
			this.@moduleQuery.Visible = visible;
        }

        private SavingTypes GetSavingType()
        {
            if (SessionManager.Current.GetSession(PageWorkshop.CURRENT_ENTITY_ID) != null)
            {
                return SavingTypes.Update;
            }

            return SavingTypes.Add;
        }

        private enum SavingTypes { Add, Update }
    }
}

